package cn.zhuoqianmingyue.login;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.zhuoqianmingyue.cache.TicketCache;
import cn.zhuoqianmingyue.pojo.User;
import cn.zhuoqianmingyue.ticket.GrantingTicket;
import cn.zhuoqianmingyue.ticket.ServiceTicket;

@Controller
@RequestMapping("/login")
public class LoginController {
	@RequestMapping("/login")
	public String login(){
		return "login/login";
	}
	@RequestMapping("/logon")
	public String logon(HttpServletRequest request,HttpServletResponse response ) throws IOException{
		
		String loginName = request.getParameter("loginName");
		String password = request.getParameter("password");
		String service = request.getParameter("service");
		
		if("lijunkui".equals(loginName)){
			
			UUID randomUUID = UUID.randomUUID();
			String ticketId = randomUUID.toString();
			GrantingTicket gt = new GrantingTicket();
			gt.setId(ticketId);
			User user = new User();
			user.setUserId(1l);
			user.setLoginName("lijunkui");
			user.setPassword("123456");
			gt.setUser(user);
			
			Cookie cookie = new Cookie("zhuoqianmingyue", ticketId);		
			cookie.setMaxAge(-1);	
			cookie.setPath("/");
			response.addCookie(cookie);
			TicketCache.putGrantingTicket(ticketId, gt);
			
			ServiceTicket st = new ServiceTicket();
			String stId = UUID.randomUUID().toString();
			st.setId(stId);
			ConcurrentHashMap<String, ServiceTicket> serviceTicketMap = gt.getServiceTicketMap();
			serviceTicketMap.put(stId, st);
			TicketCache.putSTAndGT(stId, ticketId);
			response.sendRedirect(service+"?ticket="+st.getId());
			return null;
		}
		return "login/login";
	} 
}
